<?php
namespace app\home\controller;
use think\Controller;
use think\Db;	
use think\Session;
use think\request;

/**
 *
 * 阿里支付控制器
 */
class Alipays extends Controller{

	/**
	 * 生成支付代码
	 */
	public function  getAlipaysUrl(){
		require_once EXTEND_PATH.'/alipays/config.php';
		require_once EXTEND_PATH.'/alipays/pagepay/service/AlipayTradeService.php';
		require_once EXTEND_PATH.'/alipays/pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';	
	    //商户订单号，商户网站订单系统中唯一订单号，必填
	    $out_trade_no = trim(orderNum());
	    //订单名称，必填
	    $subject = trim('充值');
	    $charge = Db::name('payments')->field('ServiceCharge')->where('id=2')->find();
	    // echo $charge['ServiceCharge'];die;
	    $charges=$_GET['amount']*$charge['ServiceCharge'];
	    $tot = $_GET['amount']+$charges;
	    // echo $tot;die;
	    // $tot = '0.01';

		$total_amount=trim(round($tot,2));

	    //商品描述，可空
	    $body = trim('余额充值');
		//构造参数
		$payRequestBuilder = new \AlipayTradePagePayContentBuilder();
		$payRequestBuilder->setBody($body);
		$payRequestBuilder->setSubject($subject);
		$payRequestBuilder->setTotalAmount($total_amount);
		$payRequestBuilder->setOutTradeNo($out_trade_no);
		$aop = new \AlipayTradeService($config);

		/**
		 * pagePay 电脑网站支付请求
		 * @param $builder 业务参数，使用buildmodel中的对象生成。
		 * @param $return_url 同步跳转地址，公网可以访问
		 * @param $notify_url 异步通知地址，公网可以访问
		 * @return $response 支付宝返回的信息
	 	*/
		$response = $aop->pagePay($payRequestBuilder,$config['return_url'],$config['notify_url']);
		// 添加数据库表单

		$data = [
			'uid'=>Session::get('uid'),
			'tradeNo'=>$out_trade_no,
			'amount'=>$_GET['amount'],
			'offline'=>1,//线上充值
			'poundage'=>round($charges,2),//手续费
			'remarks'=>'支付宝线上充值',
			'paymentCode'=>2,//支付宝对公账户
		];
		$ins = Db::name('user_recharge')->insert($data);

		if($ins){
			//输出表单
			var_dump($response);
		}

	}
	
	/**
	 * 支付结果同步回调
	*/
	public function response(){
		require_once EXTEND_PATH.'/alipays/config.php';
		require_once EXTEND_PATH.'/alipays/pagepay/service/AlipayTradeService.php';
		$arr=$_GET;
		$alipaySevice = new \AlipayTradeService($config); 
		$result = $alipaySevice->check($arr);
		if($result){
			// file_put_contents('ass.txt',json_encode($_GET));
			$out_trade_no = htmlspecialchars($_GET['out_trade_no']);
			//dump($arr);die;
			$res = Db::name('user_recharge')->where(['tradeNo'=>$out_trade_no])->find();
			if($res&&$res['paymentstate']==1){
				$this->success('充值成功',"/home/Recharge/recharge");
			}else{
				$this->error('充值失败',"/home/Recharge/recharge");
			}
		}

	}
	




}
